package com.example.micrweb.front.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.example.common.util.HttpClientUtils;
import com.example.micrweb.front.config.RealNameConfig;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.example.api.model.User;
import org.example.api.service.UserService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RealNameServiceImpl {
    @Resource
    private RealNameConfig realNameConfig;
    @DubboReference(interfaceClass = UserService.class, version = "1.0")
    private UserService userService;

    /*实名认证*/
    public boolean handlerRealName(String phone, String name, String idCard){
        String host = realNameConfig.getHost();
        String path = realNameConfig.getPath();
        String url = host + path;
        String appcode = realNameConfig.getAppcode();

        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, Object> params = new HashMap<String, Object>();

        params.put("idNo", idCard);
        params.put("name", name);

        try {
            // 调用实名认证接口
            String resp = HttpClientUtils.doPost(url, headers, params);
            if (StringUtils.isNotBlank(resp)){
                JSONObject respObject = JSONObject.parseObject(resp);
                System.out.println(respObject);
                if ("0000".equalsIgnoreCase(respObject.getString("respCode"))){
                    // 实名认证成功，更新数据库用户信息
                    Integer count = userService.modifyUserInfo(phone, name, idCard);
                    if (count == 1){
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
